package com.ky.manage.utils;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.ky.manage.constant.OverallData;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;

/**
 * 网络工具类
 */

public class NetworkUtils extends ConnectivityManager.NetworkCallback {

    private static final String TAG = NetworkUtils.class.getSimpleName();
    private static final int NETWORK_TYPE_GSM = 16;
    private static final int NETWORK_TYPE_TD_SCDMA = 17;
    private static final int NETWORK_TYPE_IWLAN = 18;
    private static StringBuffer sPingResultSB, sPingResultSB2;
    private ConnectivityManager connectivityManager;
    private NetworkConnectInterface networkConnectInterface;

    /**
     * 打开网络设置界面
     * <p>3.0以下打开设置界面</p>
     */
    public void openWirelessSettings() {
        if (Build.VERSION.SDK_INT > 10) {
            OverallData.app.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        } else {
            OverallData.app.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }

    /**
     * 获取活动网络信息
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
     *
     * @return NetworkInfo
     */
    private NetworkInfo getActiveNetworkInfo() {
        return ((ConnectivityManager) OverallData.app.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    }

    /**
     * 判断网络是否连接
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public boolean isConnected() {
        NetworkInfo info = getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

    /**
     * 判断移动数据是否打开
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public boolean getDataEnabled() {
        try {
            TelephonyManager tm = (TelephonyManager) OverallData.app.getSystemService(Context.TELEPHONY_SERVICE);
            Method getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled");
            if (null != getMobileDataEnabledMethod) {
                return (boolean) getMobileDataEnabledMethod.invoke(tm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 打开或关闭移动数据
     * <p>需系统应用 需添加权限{@code <uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>}</p>
     *
     * @param enabled {@code true}: 打开<br>{@code false}: 关闭
     */
    public void setDataEnabled(boolean enabled) {
        TelephonyManager telephonyService = (TelephonyManager) OverallData.app.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method setDataEnabled = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
            if (null != setDataEnabled) {
                setDataEnabled.invoke(telephonyService, enabled);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断网络是否是4G
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public boolean is4G() {
        NetworkInfo info = getActiveNetworkInfo();
        return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
    }

    /**
     * 判断wifi是否打开
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public boolean getWifiEnabled() {
        WifiManager wifiManager = (WifiManager) OverallData.app.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.isWifiEnabled();
    }

    /**
     * 打开或关闭wifi
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}</p>
     *
     * @param enabled {@code true}: 打开<br>{@code false}: 关闭
     */
    public void setWifiEnabled(boolean enabled) {
        try {
            WifiManager wifiManager = (WifiManager) OverallData.app.getSystemService(Context.WIFI_SERVICE);
            if (enabled) {
                if (!wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(true);
                }
            } else {
                if (wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(false);
                }
            }
        } catch (Exception e) {
        }

    }

    /**
     * 判断wifi是否连接状态
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
     *
     * @return {@code true}: 连接<br>{@code false}: 未连接
     */
    public boolean isWifiConnected() {
        ConnectivityManager cm = (ConnectivityManager) OverallData.app
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm != null && cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 判断wifi数据是否可用
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public boolean isWifiAvailable() {
        return getWifiEnabled();
    }

    /**
     * 获取网络运营商名称
     * <p>中国移动、如中国联通、中国电信</p>
     *
     * @return 运营商名称
     */
    public String getNetworkOperatorName() {
        TelephonyManager tm = (TelephonyManager) OverallData.app.getSystemService(Context.TELEPHONY_SERVICE);
        return tm != null ? tm.getNetworkOperatorName() : null;
    }

    /**
     * 获取当前网络类型
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
     *
     * @return 网络类型
     * <ul>
     * </ul>
     */
    public String getNetworkType() {
        String netType = "未知";
        NetworkInfo info = getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            int networkInfoType = info.getType();
            if (networkInfoType == ConnectivityManager.TYPE_ETHERNET) {
                netType = "以太网";
            } else if (networkInfoType == ConnectivityManager.TYPE_WIFI) {
                netType = "WiFi";
            } else if (networkInfoType == ConnectivityManager.TYPE_MOBILE) {
                int networkInfoSubType = info.getSubtype();
                switch (networkInfoSubType) {

                    case NETWORK_TYPE_GSM:
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        netType = "2G";
                        break;

                    case NETWORK_TYPE_TD_SCDMA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B:
                    case TelephonyManager.NETWORK_TYPE_EHRPD:
                    case TelephonyManager.NETWORK_TYPE_HSPAP:
                        netType = "3G";
                        break;

                    case NETWORK_TYPE_IWLAN:
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        netType = "4G";
                        break;
                    default:
                        String subtypeName = info.getSubtypeName();
                        if (!TextUtils.isEmpty(subtypeName)) {
                            if (subtypeName.equalsIgnoreCase("TD-SCDMA")
                                    || subtypeName.equalsIgnoreCase("WCDMA")
                                    || subtypeName.equalsIgnoreCase("CDMA2000")) {
                                netType = "3G";
                            } else {
                                netType = "未知";
                            }
                        } else {
                            netType = "未知";
                        }
                        break;
                }
            } else {
                netType = "未知";
            }
        }
        return netType;
    }

    public void registerNetworkCallback(NetworkConnectInterface networkConnectInterface) {
        this.networkConnectInterface = networkConnectInterface;
        NetworkRequest.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new NetworkRequest.Builder();
            NetworkRequest request = builder.build();
            connectivityManager = (ConnectivityManager) OverallData.app.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                connectivityManager.registerNetworkCallback(request, this);
            }
        }

    }

    @Override
    public void onAvailable(Network network) {
        if (networkConnectInterface != null) {
            networkConnectInterface.onAvailable(network);
        }
        super.onAvailable(network);
        EventBus.getDefault().post(new NetworkStateChangeEvent(true));
    }

    @Override
    public void onLost(Network network) { //断网
        if (networkConnectInterface != null) {
            networkConnectInterface.onLost(network);
        }
        super.onLost(network);
        EventBus.getDefault().post(new NetworkStateChangeEvent(false));
    }

    public void unregisterNetworkCallback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (connectivityManager != null) {
                connectivityManager.unregisterNetworkCallback(this);
            }
        }
    }

    public static interface NetworkConnectInterface {
        void onAvailable(Network network);

        void onLost(Network network);
    }

    public static class NetworkStateChangeEvent {
        public boolean available;

        public NetworkStateChangeEvent(boolean available) {
            this.available = available;
        }
    }
}
